//! 服务层模块
//! 提供Party相关的业务逻辑服务

use crate::client::EntityClient;
use crate::models::*;
use crate::{Result, PartyModError};
use std::collections::HashMap;
use chrono::{DateTime, Utc};

pub mod party_service;
pub mod organization_service;
pub mod customer_service;
pub mod contact_service;

pub use party_service::PartyService;
pub use organization_service::OrganizationService;
pub use customer_service::CustomerService;
pub use contact_service::ContactService;

/// 服务管理器，统一管理所有业务服务
#[derive(Clone)]
pub struct ServiceManager {
    client: EntityClient,
}

impl ServiceManager {
    /// 创建新的服务管理器
    pub fn new(client: EntityClient) -> Self {
        Self { client }
    }

    /// 获取Party服务
    pub fn party_service(&self) -> PartyService {
        PartyService::new(self.client.clone())
    }

    /// 获取组织服务
    pub fn organization_service(&self) -> OrganizationService {
        OrganizationService::new(self.client.clone())
    }

    /// 获取客户服务
    pub fn customer_service(&self) -> CustomerService {
        CustomerService::new(self.client.clone())
    }

    /// 获取联系方式服务
    pub fn contact_service(&self) -> ContactService {
        ContactService::new(self.client.clone())
    }
}

/// 通用查询条件构建器
#[derive(Debug, Clone)]
pub struct QueryBuilder {
    conditions: Vec<QueryCondition>,
    order_by: Vec<String>,
    limit: Option<i32>,
    offset: Option<i32>,
}

impl QueryBuilder {
    /// 创建新的查询构建器
    pub fn new() -> Self {
        Self {
            conditions: Vec::new(),
            order_by: Vec::new(),
            limit: None,
            offset: None,
        }
    }

    /// 添加等于条件
    pub fn eq(mut self, field: &str, value: &str) -> Self {
        self.conditions.push(QueryCondition {
            field: field.to_string(),
            operator: "=".to_string(),
            value: value.to_string(),
            logic: "AND".to_string(),
        });
        self
    }

    /// 添加模糊匹配条件
    pub fn like(mut self, field: &str, value: &str) -> Self {
        self.conditions.push(QueryCondition {
            field: field.to_string(),
            operator: "LIKE".to_string(),
            value: format!("%{}%", value),
            logic: "AND".to_string(),
        });
        self
    }

    /// 添加大于条件
    pub fn gt(mut self, field: &str, value: &str) -> Self {
        self.conditions.push(QueryCondition {
            field: field.to_string(),
            operator: ">".to_string(),
            value: value.to_string(),
            logic: "AND".to_string(),
        });
        self
    }

    /// 添加小于条件
    pub fn lt(mut self, field: &str, value: &str) -> Self {
        self.conditions.push(QueryCondition {
            field: field.to_string(),
            operator: "<".to_string(),
            value: value.to_string(),
            logic: "AND".to_string(),
        });
        self
    }

    /// 添加IN条件
    pub fn in_values(mut self, field: &str, values: &[&str]) -> Self {
        let value_str = values.join(",");
        self.conditions.push(QueryCondition {
            field: field.to_string(),
            operator: "IN".to_string(),
            value: value_str,
            logic: "AND".to_string(),
        });
        self
    }

    /// 添加排序
    pub fn order_by(mut self, field: &str, desc: bool) -> Self {
        let order = if desc {
            format!("{} DESC", field)
        } else {
            field.to_string()
        };
        self.order_by.push(order);
        self
    }

    /// 设置限制数量
    pub fn limit(mut self, limit: i32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// 设置偏移量
    pub fn offset(mut self, offset: i32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// 构建查询参数
    pub fn build(self) -> QueryParams {
        QueryParams {
            entity_name: String::new(), // 由具体服务设置
            conditions: self.conditions,
            order_by: self.order_by,
            limit: self.limit,
            offset: self.offset,
        }
    }

    /// 获取条件列表
    pub fn get_conditions(&self) -> &[QueryCondition] {
        &self.conditions
    }
}

impl Default for QueryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// 分页结果
#[derive(Debug, Clone)]
pub struct PagedResult<T> {
    pub items: Vec<T>,
    pub total_count: Option<i64>,
    pub page_size: i32,
    pub page_number: i32,
    pub has_next: bool,
    pub has_previous: bool,
}

impl<T> PagedResult<T> {
    /// 创建新的分页结果
    pub fn new(items: Vec<T>, total_count: Option<i64>, page_size: i32, page_number: i32) -> Self {
        let has_next = if let Some(total) = total_count {
            (page_number * page_size) < total as i32
        } else {
            items.len() == page_size as usize
        };
        
        let has_previous = page_number > 1;

        Self {
            items,
            total_count,
            page_size,
            page_number,
            has_next,
            has_previous,
        }
    }

    /// 获取总页数
    pub fn total_pages(&self) -> Option<i32> {
        self.total_count.map(|total| {
            ((total as f64) / (self.page_size as f64)).ceil() as i32
        })
    }
}

/// 通用工具函数
pub mod utils {
    use super::*;

    /// 生成新的Party ID
    pub fn generate_party_id() -> String {
        // 生成一个短的随机ID，确保不超过20字符限制
        let uuid = uuid::Uuid::new_v4().to_string().replace("-", "");
        // 取UUID的前12个字符，加上前缀总共18个字符，符合20字符限制
        format!("PARTY_{}", &uuid[..12].to_uppercase())
    }

    /// 生成新的联系机制ID
    pub fn generate_contact_mech_id() -> String {
        format!("CM_{}", uuid::Uuid::new_v4().to_string().replace("-", "").to_uppercase())
    }

    /// 验证邮箱格式
    pub fn is_valid_email(email: &str) -> bool {
        email.contains('@') && email.contains('.')
    }

    /// 验证电话号码格式（简单验证）
    pub fn is_valid_phone(phone: &str) -> bool {
        phone.chars().all(|c| c.is_ascii_digit() || c == '-' || c == '(' || c == ')' || c == ' ' || c == '+')
    }

    /// 格式化全名
    pub fn format_full_name(first_name: Option<&str>, middle_name: Option<&str>, last_name: Option<&str>) -> String {
        let mut parts = Vec::new();
        
        if let Some(first) = first_name {
            if !first.is_empty() {
                parts.push(first);
            }
        }
        
        if let Some(middle) = middle_name {
            if !middle.is_empty() {
                parts.push(middle);
            }
        }
        
        if let Some(last) = last_name {
            if !last.is_empty() {
                parts.push(last);
            }
        }
        
        parts.join(" ")
    }

    /// 格式化地址
    pub fn format_address(
        address1: Option<&str>,
        address2: Option<&str>,
        city: Option<&str>,
        state: Option<&str>,
        postal_code: Option<&str>,
        country: Option<&str>
    ) -> String {
        let mut parts = Vec::new();
        
        if let Some(addr1) = address1 {
            if !addr1.is_empty() {
                parts.push(addr1.to_string());
            }
        }
        
        if let Some(addr2) = address2 {
            if !addr2.is_empty() {
                parts.push(addr2.to_string());
            }
        }
        
        let mut location_parts = Vec::new();
        if let Some(c) = city {
            if !c.is_empty() {
                location_parts.push(c);
            }
        }
        if let Some(s) = state {
            if !s.is_empty() {
                location_parts.push(s);
            }
        }
        if let Some(pc) = postal_code {
            if !pc.is_empty() {
                location_parts.push(pc);
            }
        }
        
        if !location_parts.is_empty() {
            parts.push(location_parts.join(", "));
        }
        
        if let Some(country_name) = country {
            if !country_name.is_empty() {
                parts.push(country_name.to_string());
            }
        }
        
        parts.join(", ")
    }
}